# coding=utf-8
import numpy as np
from mindspore import Tensor, context
from mindspore import dtype as mstype
context.set_context(mode=context.GRAPH_MODE, device_target="CPU")

x = Tensor(0.1)

# 从NumPy数组生成
arr = np.array([1, 0, 1, 0])
x_np = Tensor(arr)

# 使用init初始化器构造张量
from mindspore import Tensor
from mindspore import set_seed
from mindspore import dtype as mstype
from mindspore.common.initializer import One, Normal

set_seed(1)

tensor1 = Tensor(shape=(2, 2), dtype=mstype.float32, init=One())
tensor2 = Tensor(shape=(2, 2), dtype=mstype.float32, init=Normal())
print(tensor1)
print(tensor2)

# 继承另一个张量的属性，形成新的张量
from mindspore import ops
oneslike = ops.OnesLike()
x = Tensor(np.array([[0, 1], [2, 1]]).astype(np.int32))
output = oneslike(x)
print(output)

# 输出指定大小的恒定值张量
import mindspore.ops as ops

shape = (2, 2)
ones = ops.Ones()
output = ones(shape, mstype.float32)
print(output)

zeros = ops.Zeros()
output = zeros(shape, mstype.float32)
print(output)

# 张量的属性
t1 = Tensor(np.zeros([1, 2, 3]), mstype.float32)
print("Datatype of tensor: {}".format(t1.dtype))
print("Shape of tensor: {}".format(t1.shape))

# 张量之间有很多运算，包括算术、线性代数、矩阵处理（转置、标引、切片）、采样等，下面介绍其中几种操作，张量运算和NumPy的使用方式类似。
tensor = Tensor(np.array([[0, 1], [2, 3]]).astype(np.float32))
print("First row: {}".format(tensor[0]))
print("First column: {}".format(tensor[:, 0]))
print("Last column: {}".format(tensor[..., -1]))
# Concat将给定维度上的一系列张量连接起来。
data1 = Tensor(np.array([[0, 1], [2, 3]]).astype(np.float32))
data2 = Tensor(np.array([[4, 5], [6, 7]]).astype(np.float32))
op = ops.Concat()
output = op((data1, data2))
print(output)
# Stack则是从另一个维度上将两个张量合并起来。
data1 = Tensor(np.array([[0, 1], [2, 3]]).astype(np.float32))
data2 = Tensor(np.array([[4, 5], [6, 7]]).astype(np.float32))
op = ops.Stack()
output = op([data1, data2])
print(output)
# 普通运算：
input_x = Tensor(np.array([1.0, 2.0, 3.0]), mstype.float32)
input_y = Tensor(np.array([4.0, 5.0, 6.0]), mstype.float32)
mul = ops.Mul()
output = mul(input_x, input_y)
print(output)

# 张量转换为NumPy
zeros = ops.Zeros()
output = zeros((2, 2), mstype.float32)
print("output: {}".format(type(output)))
n_output = output.asnumpy()
print("n_output: {}".format(type(n_output)))
# NumPy转换为张量
output = np.array([1, 0, 1, 0])
print("output: {}".format(type(output)))
t_output = Tensor(output)
print("t_output: {}".format(type(t_output)))
